
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>

#define _STEP_MOTORY    1

int fd;
int step_fsm_flag = 0;

#ifdef _STEP_MOTORY
unsigned char CCW[8]={0x08,0x0c,0x04,0x06,0x02,0x03,0x01,0x09}; //逆时钟旋转相序表
unsigned char CW[8]={0x09,0x01,0x03,0x02,0x06,0x04,0x0c,0x08};  //正时钟旋转相序表
#else
unsigned char CCW[4]={0x10,0x08,0x040,0x02};//反转表格
unsigned char CW[4]={0x02,0x04,0x08,0x10};//正转表格
#endif

void step_motor_test(int fd)
{
	int i,j;
    int ret;
    // 正转2圈，反转2圈
    switch(step_fsm_flag)
    {
        case 0:
        case 1:
        {
            printf(" CW count: %d\n",step_fsm_flag+1);
            for(j = 0; j<64; j++)
            {
                #ifdef _STEP_MOTORY
                for(i=0; i<8; i++)
                #else 
                for(i=0; i<4; i++)
                #endif
                {
                    ret = write(fd, CW+i, 1);
                    if(ret == 1)
                    {
                        //printf("CW Step = %d\n", i+1);   
                    }
                    usleep(100000); // 100ms
                }
            }
            step_fsm_flag++;
            break;
        }
        case 2:
        case 3:
        {
            printf(" CCW count: %d\n",step_fsm_flag+1);
            for(j =0; j<64; j++)
            {
                #ifdef _STEP_MOTORY
                for(i=0; i<8; i++)
                #else 
                for(i=0; i<4; i++)
                #endif
                {
                    ret = write(fd, CCW+i, 1);
                    if(ret == 1)
                    {
                        printf("CCW Step = %d\n", i+1);   
                    }
                    usleep(100000); // 100ms
                }
            }
            step_fsm_flag++;
            if(step_fsm_flag>=3)
                step_fsm_flag = 0;

            break;
        }
        default:
            printf("invalid param\n");
            break;
    }
}


/*
 * ./step-motor_test /dev/mystepmotor
 *
 */
int main(int argc, char **argv)
{
    int flags;
    int val;
    int ret;
    int i;
    
    /* 1. 判断参数 */
    if (argc != 2) 
    {
        printf("Usage: %s <dev>\n", argv[0]);
        return -1;
    }

    /* 2. 打开文件 */
    fd = open(argv[1], O_RDWR);
    if (fd == -1)
    {
        printf("can not open file %s\n", argv[1]);
        return -1;
    }

    
    while (1)
    {
        //step_motor_test(fd);
        #ifdef _STEP_MOTORY
        for(i=0; i<8; i++)
        #else 
        for(i=0; i<4; i++)
        #endif
        {
            ret = write(fd, CCW+i, 1);
            if(ret == 1)
            {
                //printf("CW Step = %d\n", i+1);   
            }
            usleep(100000); // 100ms
        }
    }
    
    close(fd);
    
    return 0;
}


